/**
 * 验证工具
 */

interface ValidatorHandler {
  (val: string | number): boolean;
}

interface ValidatorParam {
  handler: boolean;
  errorMsg: string;
}

export const mergeValidator = (list: ValidatorParam[]): string => {
  let msg = "";
  list.find((item) => {
    if (item.handler) {
      msg = item.errorMsg;
      return true;
    }
  });
  return msg;
};

// 电话号码
export const phoneReg = /^1[0-9]{10}$/;
export const phoneValidator: ValidatorHandler = (val) => {
  return phoneReg.test(val as string);
};

// 邮箱
export const mailRes = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
export const mailValidator: ValidatorHandler = (val) => {
  return mailRes.test(val as string);
};

// 纯数字
export const allNumberRes = /^\d{1,}$/;
export const allNumberValidator: ValidatorHandler = (val) => {
  return allNumberRes.test(val as string);
};

// 小数点后两位
export const twoDecimalReg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{2})$/;
export const twoDecimalValidator: ValidatorHandler = (val) => {
  return twoDecimalReg.test(val as string);
};

// 纯中文
export const allChineseReg = /^[\u4e00-\u9fa5]{1,}$/;
export const allChineseValidator: ValidatorHandler = (val) => {
  return allChineseReg.test(val as string);
};

// 包含中文
export const hasChineseReg = /[\u4e00-\u9fa5]/;
export const hasChineseValidator: ValidatorHandler = (val) => {
  return hasChineseReg.test(val as string);
};

// 是否有前后空格
export const hasSideBlankReg = /^\s+|\s+$/;
export const hasSideBlankValidator: ValidatorHandler = (val) => {
  return hasSideBlankReg.test(val as string);
};

// 是否为空字符串
export const blankStringValidator: ValidatorHandler = (val) => {
  return !val || !(val as string).trim();
};

// 中文、字母、数字 组合
export const chineseLetterNumberReg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/;
export const chineseLetterNumberValidator: ValidatorHandler = (val) => {
  return chineseLetterNumberReg.test(val as string);
};

// 长度校验
interface LengthValidatorOptions {
  min?: number;
  max?: number;
  // 去除前后空格
  isTrim?: boolean;
}

export const lengthValidator = (val: any, opts: LengthValidatorOptions) => {
  const options = Object.assign(
    {
      min: -Infinity,
      max: Infinity,
      isTrim: true,
    } as LengthValidatorOptions,
    opts
  );

  const len = (function () {
    if (typeof val === "string") {
      return options.isTrim ? val.trim().length : val.length;
    } else if (typeof val === "number") {
      return Number(val).toString().length;
    }
    return 0;
  })();

  return len >= options.min && len <= options.max;
};

// 是否合法的时间字符串
export const dateTimeValidator: ValidatorHandler = (val) => {
  return !!(val && new Date(String(val)).toString() !== "Invalid Date");
};
